from NodeMap import NodeMap
import hashlib

class ConsistentHashing:
    
    def __init__(self):
        self.__md5 = hashlib.md5()

    def hash(self, key):
        assert(key is not None)
        self.__md5.update(key.encode(encoding='utf-8'))
        bKey = self.__md5.digest()
        return int.from_bytes(bKey[0:4], 'little')

import unittest
class TestConsistentHashing(unittest.TestCase):
        
    def testHash(self):
        ch = ConsistentHashing()

        # create nodeMap  Move to static create
        nodeMap = NodeMap()
        nodes = ["192.168.2.1", "192.168.2.3"]
        for n in nodes:
            for i in range(160):
                key = '%s-%d' % (n, i)
                nodeMap.insert(ch.hash(key), n)
        print(nodeMap)

        print(0, nodeMap.firstbigThan(0))
        print(4283090998, nodeMap.firstbigThan(4283090998))

        def printUser(user, ch, nodeMap):
            userHash = ch.hash(user)
            print(user, userHash, nodeMap.firstbigThan(userHash))
            
        # find user=abc123 's Node
        printUser('abc123', ch, nodeMap)
        printUser('abc124', ch, nodeMap)
        printUser('abc125', ch, nodeMap)
        printUser('abc126', ch, nodeMap)
        printUser('abc127', ch, nodeMap)
        printUser('abc128', ch, nodeMap)
        printUser('abc129', ch, nodeMap)
        printUser('abc130', ch, nodeMap)


if __name__ == "__main__":
    suite = unittest.TestSuite([
        unittest.TestLoader().loadTestsFromTestCase(TestConsistentHashing),
        ])
    unittest.TextTestRunner(verbosity=2).run(suite)
